package com.miao.im.config;

import com.miao.im.support.mq.MqMessageFailedStore;
import com.miao.im.support.mq.MqMessagePayload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnsCallback;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/3/11 10:52
 * @Description:
 */
@Configuration
@ConditionalOnClass(RabbitTemplate.class)
@Slf4j
public class RabbitBaseConfiguration implements ConfirmCallback, ReturnsCallback {

    @Bean
    @Scope("prototype")
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        return new RabbitTemplate(connectionFactory);
    }


    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String s) {
        if (ack) {
            log.info("消息成功到达Exchange");
        } else {
            if (correlationData instanceof MqMessagePayload) {
                MqMessagePayload messageCorrelationData = (MqMessagePayload)correlationData;
                MqMessageFailedStore.add(messageCorrelationData);
            }
        }
    }

    @Override
    public void returnedMessage(ReturnedMessage returned) {
        log.info("消息报文:{}\n" +
                "消息编号:{}\n" +
                "描述:{}\n" +
                "交换机名称:{}\n" +
                "路由名称:{}",
                new String(returned.getMessage().getBody()),
                returned.getReplyCode(),
                returned.getReplyText(),
                returned.getExchange(),
                returned.getRoutingKey()
        );
    }
}
